# 此模块负责下载器的链接处理逻辑

import urllib.parse
import os.path


class Link:

    def __init__(self, link):
        """
        init
        """
        self.__main_link = link

    def set_link(self, link):
        """
        设置新链接
        """
        self.__main_link = link

    def get_domainname(self) -> str:
        """
        从链接中获取域名部分
        """
        url = urllib.parse.urlparse(self.__main_link)
        domain_name = url.netloc if not url.netloc is '' else ''
        return domain_name

    def get_path(self) -> str:
        """
        从链接中获取的资源路径
        """
        url = urllib.parse.urlparse(self.__main_link)
        path = url.path if not url.path is '' else None
        return path

    def get_filename(self) -> str:
        """
        从链接中截取文件名
        """
        path = urllib.parse.urlparse(self.__main_link).path
        # print(os.path.basename(path))
        return os.path.basename(path)

    def fix_link(self, template) -> str:
        """
        尝试修复不完整的链接
        :template: 修复url使用的url模板(通常是一个完整的url)
        """
        if self.__main_link == '':
            return None
        if self.__main_link[0] == '.':
            n = 0
            for s in self.__main_link:
                if s == '.':
                    n += 1
                else:
                    break
            path = self.__fix_link_path(template, n)
            url = path + self.__main_link[n+1:]
        
        elif self.__main_link[0:2] == '//':
            parse = urllib.parse.urlparse(template)
            url = parse.scheme + ':' + self.__main_link

        elif self.__main_link[0] == '/':
            parse = urllib.parse.urlparse(template)
            url = parse.scheme + '://' + parse.netloc + self.__main_link
        else:
            url = self.__main_link
        
        return url

    def __fix_link_path(self, link, n) -> str:
        """
        为链接路径寻找上级路径
        :n: 向上 n 级
        """
        n -= 1
        path = urllib.parse.urlparse(link).path
        base = os.path.basename(path)
        new = link.replace(base, '')
        if n > 0:
            if new[-1] is '/':
                return self.__fix_link_path(new[0:-1], n)
            else:
                return self.__fix_link_path(new, n)
        else:
            return new
